// Cookie 操作者
export class CookieOperator {
    //region # 方法

    /**
     * 设置
     * @param obj - 存储实体
     * @param exMillisecond - 失效时间
     * */
    public Set(obj:object, exMillisecond:number = 0) {
        // 设置超时时间
        if (exMillisecond > 0) {
            const dateNow:Date = new Date()
            const time:number = dateNow.getTime() + exMillisecond
            const expiresTime:string = new Date(dateNow.setTime(time)).toUTCString()
            Object.assign(obj, { expires: expiresTime })
        }

        // 获取存储字符串
        const entries = Object.entries(obj)
        const entriesArry = entries.map((item) => `${item[0]}=${item[1]}`)

        // 设置 Cookie
        document.cookie = entriesArry.join(';')
    }

    /**
     * 获取
     * */
    public get() {
        const result:{ [key:string]:string } = {}
        const cookieArray = document.cookie.split(';')

        // 遍历设置对象
        cookieArray.forEach((item) => {
            if (item.indexOf('expires=') == -1) {
                const trimmedItem = item.trim()
                const separatorIndex = trimmedItem.indexOf('=')

                if (separatorIndex !== -1) {
                    const itemArray = item.split('=')
                    const exMinutes = itemArray[0]
                    result[exMinutes] = itemArray[1]
                }
            }
        })

        return result
    }

    //endregion
}
